#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
    const int INF=0x3f3f3f3f;
    typedef pair<int,int> pii;
    int minTime(int n, vector<vector<int>>& edges) {
        vector<vector<tuple<int,int,int>>> g(n);
        for(auto& e:edges)
            g[e[0]].emplace_back(e[1],e[2],e[3]);
        vector<int> d(n,INF);
        d[0]=0;
        priority_queue<pii,vector<pii>,greater<>> q;
        q.emplace(0,0);
        while(!q.empty())
        {
            auto [t_x,x]=q.top();
            q.pop();
            if(t_x>d[x]) continue;
            for(auto& [y,start,end]:g[x])
            {
                if(t_x>=start&&t_x<=end&&t_x+1<d[y])
                {
                    d[y]=t_x+1;
                    q.emplace(d[y],y);
                }
                if(t_x<start&&start+1<d[y])
                {
                    d[y]=start+1;
                    q.emplace(d[y],y);
                }
            }
        }
        return d[n-1]==INF?-1:d[n-1];

    }
};